#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: jixin
# @Date:   2016-03-10 13:30:50
# @Last Modified by:   anchen
# @Last Modified time: 2016-03-10 16:34:57
import sys
import socket
import select
import threading

class ChatClient():
    def __init__(self, host,port):
        self.socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.socket.connect((host,port))
        self.readfunc=self.socket.makefile('rb',0)
        self.writefunc=self.socket.makefile('wb',0)

        flag=True
        while flag:
            try:
                response=self.readfunc.readline().decode('utf-8')
                if response.startswith("Please input your nickname"):
                    print(response)
                    nickname=raw_input("nickname:")
                    if nickname:
                        self.writefunc.write((nickname + '\r\n').encode('utf-8'))
                        resp=self.readfunc.readline().decode('utf-8')
                        print resp
                        if resp.startswith("Welcome"):
                            flag=False
                else:
                    raise Exception("Server error")
            except:
                print(response)
        self.writefunc.write(('/allusers\r\n').encode('utf-8'))
        print("Currently in the chat room:", self.readfunc.readline().decode('utf-8').strip())
        self.run()
    

    def run(self):
        sendmsgThread = SendMsgThread(self.writefunc)
        sendmsgThread.start()

        msgdata=True
        while msgdata:
            msgdata = self.readfunc.readline().decode('utf-8')
            if msgdata:
                print(msgdata.strip())
        sendmsgThread.flag = True

class SendMsgThread(threading.Thread):
    def __init__(self, writefunc):
        threading.Thread.__init__(self)
        self.setDaemon(True)
        self.sendmsg=writefunc
        self.flag=False

    def run(self):
        while not self.flag:
            msgText = sys.stdin.readline().strip()
            if msgText:
                self.sendmsg.write((msgText+'\r\n').encode('utf-8'))

if __name__ == '__main__':
    Host='localhost'
    Port=9999
    ChatClient(Host,Port)